<?php
/**
 * Created by PhpStorm.
 * User: Inhere
 * Date: 2015/1/28
 * Use : ...
 * File: Module.php
 */

namespace ulue\cli;

use Ulue;
use ulue\cli\Application;
use ulue\cli\Controller;
use ulue\core\TheSystemException;

class Module extends AbstractModule
{
    public $defaultController       = 'default';

    /**
     * 得到控制器对象 get controller object $this->controller
     * @param $name
     * @param Application $app
     * @throws TheSystemException
     * @throws \DRuntimeException
     * @return Controller
     */
    public function activeController($name, Application $app)
    {
        if (!$name) {
            throw new \DRuntimeException("Error Processing Request");
        }

        $moduleName = $this->name;
        $controllerUrl  = '/'.$moduleName.'/'.$name;

        // 命名空间跟着模块走，因为模块不一定在 src 目录
        $namespace      = dirname($this->id);

        /**
         * 特殊情况，访问默认模块
         * @var $app Application
         */
        if ($moduleName == $app->defaultModule) {
            $controllerUrl = '/'.$name;
            // $namespace     = $moduleName;
        }

        $isSimple    = $app->isSimple;
        $cliDirname  = 'console';
        $cDirname    = $isSimple ? 'commands' : 'controllers';
        $suffix      = $isSimple ? 'Command' : $app->get('suffix.controller');
        $parentClass = 'ulue\core' . ($isSimple ? '\cli\SimpleApplication' : '\controller\cli\Controller');

        $namespace      .= "\\$cliDirname\\$cDirname\\";
        $filename        = ucfirst($name).$suffix;
        static $_control = array();

        // 组装含命名空间的 完整控制器类名 admin\controllers\DefaultController
        $id = $fullClassname = $namespace . $filename;

        if ( isset($_control[$fullClassname]) && !empty($_control[$fullClassname]) ) {
            return $_control[$fullClassname];
        }

        $fullPath       = $this->path."/$cliDirname/$cDirname/$filename.php";

        // 控制器类检查
        $this->checkIsCorrectClass($fullPath, $fullClassname, $parentClass,$isSimple ? '命令类':'命令控制器');

        /**
         * 实例化控制类
         * @var $controller Controller
         */
        $_control[$fullClassname] = $controller  = new $fullClassname();

        $controller->setPath( dirname($fullPath) )->setName($name)->setRoute($controllerUrl);


        unset($arr,$controllerDir,$fullClassname,$fullPath,$cliDirname,$cDirname, $suffix, $parentClass);

        return $controller;
    }

}// end class Module